<template>
  <div class="comment-page">
    <van-nav-bar title="商品评价" left-text="返回" left-arrow @click-left="onClickLeft" />
    <van-list>
      <van-cell title="评分" :value="rate">
        <template #right-icon>
          <van-rate v-model="rate" show-score />
        </template>
      </van-cell>
      <van-field
        label="评论内容"
        type="textarea"
        rows="4"
        maxlength="200"
        v-model="content"
      />
      <van-cell title="上传图片">
        <template #right-icon>
          <van-uploader
            :max-count="1"
            :after-read="beforeRead"
            v-model="fileList"
            accept="image/*"
            :preview-size="[60, 40]"
            multiple
          >
            <van-icon name="photo-o" />
          </van-uploader>
        </template>
      </van-cell>
      <van-button type="primary" block round @click="onSubmit">提交</van-button>
    </van-list>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { remark, getToken } from "@/api/shop";
import { useRoute, useRouter } from "vue-router";
import { toast, close } from "@/util/toast";
import axios from "axios";
const fileList = ref([]);
const imageUrl = ref("");
const content = ref("");
const rate = ref(0);
const route = useRoute();
const router = useRouter();
const onSubmit = async () => {
  const shop_id = route.query.shop_id;
  toast("loading", "评论提交中", 10000);
  await remark({
    shop_id,
    remark: content.value,
    rate: rate.value,
    remark_img: imageUrl.value,
  }).then(() => {
    close();
    router.back();
  });
};
const onClickLeft = () => {
  router.back();
};

// cdn域名
const cdnDomin = "rticjscfv.hn-bkt.clouddn.com";
const beforeRead = (req) => {
  console.log(req);
  if (!["image/webp", "image/png", "image/jpeg"].includes(req.file.type)) {
    toast("fail", "请上传正确的图片格式", 1000);
    return false;
  } else if (req.file.size / 1024 / 1024 > 2) {
    toast("fail", "图片大小应该小于2MB", 1000);
    return false;
  }
  const config = {
    headers: { "Content-Type": "multipart/form-data" },
  };
  const fileType = req.file.type.slice(6);
  const keyname = "remark" + new Date().getTime() + "." + fileType;
  getToken().then((res) => {
    const formdata = new FormData();
    formdata.append("file", req.file);
    formdata.append("token", res.data.token);
    formdata.append("key", keyname);

    // 获取到凭证之后再将文件上传到七牛云空间
    axios.post("https://upload-z2.qiniup.com", formdata, config).then((res) => {
      imageUrl.value = "http://" + cdnDomin + "/" + res.data.key;
      // fileList.value.push(imageUrl);
      console.log(imageUrl);
    });
  });
};
</script>

<style scoped>
.comment-page {
  height: 100%;
}

textarea {
  font-size: 14px;
  line-height: 1.5;
}
.van-cell {
  text-align: left;
}
</style>
